<?php

namespace UploadBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{

    public function indexAction(Request $request)
    {
        $path       = $this->getParameter('kernel.root_dir');

        $data       = $request->get('data');

        $current    = $data['currentChunk'];
        $file       = $path.'/../upload/sliceUploader/'.$data['fileName'];

        if($current==0 && file_exists($file)) {
            unlink($file);
        }


        $fileData   = base64_decode($data['fileData']);
        $fileData   = substr($fileData, 13);
        $fileData   = base64_decode($fileData);


        file_put_contents($file, $fileData, FILE_APPEND);


        unset($data['fileData']);


        if($data['currentChunk'] == $data['chunks']) {
            $data['serverMd5'] = md5_file($file);
            if($data['serverMd5'] !== $data['md5sum']) {
                $data['success'] = false;
            }
        }


        $data['currentChunk'] = $data['currentChunk'] + 1;



        $response   =  new Response(json_encode($data));

        $response->headers->set('Access-Control-Allow-Origin', '*');

        return $response;
    }
}
